﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WorkTool
{
	public partial class HexConverter : UserControl
	{
		public HexConverter()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (txtHex.Text.Length > 0)
			{
				try
				{
					if (txtHex.Text.ToLower().StartsWith("0x") && txtHex.Text.Length > 2) 
						txtHex.Text = txtHex.Text.Substring(2);
					txtAscii.Text = ConvertHexToAscii(txtHex.Text);
				}
				catch
				{
					txtAscii.Text = "Error";
				}
			}

			else if (txtAscii.Text.Length > 0)
			{
				try
				{
					txtHex.Text = ConvertAsciiToHex(txtAscii.Text);
				}
				catch
				{
					txtHex.Text = "Error";
				}
			}

		}
		public string ConvertHexToAscii(string Hex)
		{
			if (!(Hex.Length % 2 == 0)) Hex += "0";
			string ReturnStr = "";

			for (int ptr = 0; ptr < Hex.Length; ptr++)
			{ // Every other character, convert this two-character hex byte.
				if (!(ptr % 2 == 0))
				{ // Convert from Hex to Dec (int.parse), then from Dec to ASCII (.ToChar)
					ReturnStr += Convert.ToChar(
						int.Parse(Hex.Substring(ptr - 1, 2),
						System.Globalization.NumberStyles.HexNumber));
				}
			}
			return ReturnStr;
		}

		public string ConvertAsciiToHex(string txt)
		{
			string ReturnStr = "";
			for (int ptr = 0; ptr < txt.Length; ptr++)
			{
				// Convert char to dec ((int)char), then dec to hex (.ToString("X"))
				ReturnStr += ((int)txt[ptr]).ToString("X");
			}
			return ReturnStr;
		}
	}
}
